package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    /*从Spring容器中获取一个RestTemplate对象
    基于此对象实现远端服务调用*/
    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.application.name:sca-consumer}")
    private String appName;

    @GetMapping("/consumer/doRestEcho01")
    public String doRestEcho01() {
        String url = "http://localhost:8081/provider/echo/tedu";
        return restTemplate.getForObject(url,
                String.class/*远端url对应的方法返回值类型*/);
    }

    // @GetMapping("/consumer/doRestEcho01")
    // public String doRestEcho01(){/*自己实现负载均衡  但是这个方法不够灵活，每次启动一个新的服务都需要修改代码*/
    //   String url1="http://localhost:8081/provider/echo/tedu";
    //   String url2="http://localhost:8082/provider/echo/tedu";
    //    String[]urls={url1,url2};
    //     String url=urls[new Random().nextInt(2)];/*随机算法*/
    //    return restTemplate.getForObject(url,
    //            String.class/*远端url对应的方法返回值类型*/);
    // }
    /*
     * 负载均衡客户端对象，基于此对象可以获得nacos中的服务实例
     * 并且通过负载均衡算法从所有实例中取一个实例*/
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho2() {
        /*从nacos中获取服务实例(这里的choose方法内置了负载均衡算法)*/
        ServiceInstance instance =
                loadBalancerClient.choose("sca-provider");
        String ip = instance.getHost();
        int port = instance.getPort();
        //String url="http://"+ip+":"+port+"/provider/echo/"+appName;  不推荐这么写
        String url =
                String.format("http://%s:%s/provider/echo/%s", ip, port, appName);/*--------------------------------------------------*/
        return restTemplate.getForObject(url,
                String.class/*远端url对应的方法返回值类型*/);
    }




}
